package Server.ServerCore.Controller;

import Server.ServerCore.Model.AI.BankerAI;
import Server.ServerCore.Model.Player.PlayerInstance;
import Server.ServerCore.Model.vo.CardResultStatusVO;
import Server.ServerCore.Model.vo.CardVO;
import Server.ServerCore.Repository.ChipsServiceImpl;
import Server.ServerCore.Service.DataPacks.packRequest.Over_requst;
import Server.ServerCore.Service.DataPacks.packRespose.Chips_reback_Response;
import Server.ServerCore.Service.DataPacks.packRespose.OverChips_response;
import Server.ServerCore.Service.DataPacks.packRespose.Over_response;
import Server.ServerCore.Service.Logic.HandleController;
import Server.ServerCore.Service.Logic.RegisterPack;
import Server.ServerCore.Service.service.PlayerManagerService;
import Server.ServerCore.Service.usyns.SingelTableManager;
import javolution.util.FastList;
import org.jboss.netty.buffer.ChannelBuffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author :石头哥哥<br/>
 *         Project:21Server
 *         Date: 13-4-17
 *         Time: 下午9:59
 *
 *     如果玩家所有牌爆牌，那么庄家直接收取筹码，此controller将不会被调用
 *     那么资源将不会被回收，故在下次发牌前，清理下资源
 *         筹码结算
 */
@Service
public class OverController  extends HandleController {

    private Logger logger= LoggerFactory.getLogger(OverController.class);
    @Resource
    private ChipsServiceImpl chipsService;
    @Resource
    private SingelTableManager singelTableManager;


    /**
     * 数据分解具体处理的函数
     *       //找出circleUnitID位置牌的总点数，和庄家比较  21  20
     //1：点数比较（1：1），2：庄家黑杰克（2倍保险），3：玩家黑杰克（2.5）,4:lost
     //如果玩家输了，则不减，赢了则加上筹码；
     //已排序,找出玩家指定位置上的牌并计算出总点数，和庄家比较，注意，此时的所有牌都没有爆牌
     //获取庄家的点数
     * @param buffer buffer
     * @param player player
     */
    @Override
    public void DispatchPack(ChannelBuffer buffer, PlayerInstance player) throws Exception {
            Over_requst overRequst= (Over_requst) parseObject(buffer,Over_requst.class);
            BankerAI bankerAI =singelTableManager.getBankerAI(player);
            int bankerPoints=bankerAI.getPoints();
            //庄家是否黑杰克
            boolean bankAIBlack=false;
            if ( bankerAI.getCardVOFastList().size()==2&&bankerPoints==21){
                bankAIBlack=true;
            }
            FastList<Over_response> Result_list=new FastList<Over_response>();//响应数据链表
            double  totalChips=0;
            for (Integer circleUnitID:overRequst.getList()){
                if (player.getDeckoOfCardsVOFastList()!=null){
                    CardResultStatusVO cardResultStatusVO=player.getDeckoOfCardsVOFastList()[circleUnitID];
                    if (cardResultStatusVO.getBust()!=1){//玩家没有爆牌
                        int playerPoints=cardResultStatusVO.getPoints();
                        Over_response overResponse=new Over_response();
                        overResponse.setCircleUnitID(circleUnitID);
                        byte lost;//0:lost
                        double Chips = 0;
                        double tempChips=cardResultStatusVO.getChipsPoints();//每副牌的筹码数
                        //解析玩家是否是黑杰克 如果庄家和玩家都是黑杰克，那么庄家赢
                        boolean blackPlayer=false;
                        FastList<CardVO> temp1=new FastList<CardVO>();//player blackjack
                        for (CardVO card:player.getCardVOFastList()){
                            if (card.getCircleUnitID()==circleUnitID){
                                temp1.add(card);
                            }
                        }
                        if (temp1.size()==2&&playerPoints==21&&!cardResultStatusVO.isIsspush()){
                            blackPlayer=true;
                        }
                        temp1.clear();
//                        temp2.clear();
//                1.平手 lost=2；
//                2.庄家赢  lost=0；
//                3.玩家赢  lost=1；  以上3个条件，互斥
                        if (playerPoints==bankerPoints&&bankerPoints<=21&&playerPoints<=21&&!bankAIBlack&&!blackPlayer||blackPlayer&&bankAIBlack){//打和
                            lost=2;
                            Chips=tempChips;
                            overResponse.setLost(lost);
                            overResponse.setChips(Chips);
//                            System.out.println("平手--》》"+"庄点数："+ bankerPoints+" 玩家点数："+ playerPoints);

                        }else if (bankerPoints>playerPoints&&bankerPoints<=21&&playerPoints<=21||bankAIBlack&&!blackPlayer){//庄家赢（注意买了保险的玩家）
                            lost=0;
                            Chips=0;
                            overResponse.setLost(lost);
                            overResponse.setChips(0);
//                            System.out.println("庄家赢--》》"+"庄点数："+ bankerPoints+" 玩家点数："+ playerPoints);

                        }else if (playerPoints>bankerPoints&&playerPoints<=21&&bankerPoints<=21||bankerPoints>21||blackPlayer&&!bankAIBlack){
                            lost=1;
                            if (blackPlayer){
//                                System.out.println("当前牌的筹码数：--->>>>"+tempChips);
                                Chips=tempChips*2.5;
//                                System.out.println("2.5的筹码数：--->>>>"+Chips);
                                overResponse.setLost(lost);
                                overResponse.setChips(Chips);
                            }else {
//                                System.out.println("当前牌的筹码数：--->>>>"+tempChips);
                                Chips=tempChips*2;
//                                System.out.println("2倍的筹码数：--->>>>"+Chips);
                                overResponse.setLost(lost);
                                overResponse.setChips(Chips);

                            }
//                            System.out.println("玩家赢--》》"+"庄家点数："+ bankerPoints+"玩家点数："+ playerPoints);
                        }
                        totalChips+=Chips;//牌桌筹码
                        Result_list.add(overResponse);
                    }
                }else {
                    return;
                }
            }
            totalChips+=player.getBargainingChip();//玩家筹码总额
            chipsService.updateChips(player.getGameRole(), totalChips);

            player.setBargainingChip(totalChips);
//            System.out.println("over筹码余额：--->>>>"+totalChips);

            //返回牌局结束计算信息
            OverChips_response overChipsResponse=new OverChips_response();
            overChipsResponse.setResult_list(Result_list);
            player.DirectSend(overChipsResponse.getJsonData(2,6));


            //返回筹码余额包
            Chips_reback_Response rebackResponse=new Chips_reback_Response();
            rebackResponse.setChips(totalChips);
            player.DirectSend(rebackResponse.getJsonData(2,7));

            //牌局结束标记
            player.setOver(true);
            player.setBet(false);

            //牌局结束，清空数据资源
            PlayerManagerService.clear(player);



    }

    /**
     * 通过spring产生处理数据的controller，储存在数组中
     */
    @Override
    public void InitiController() {
        RegisterPack.GAME_CONTROLLERS[218]=this;
    }
}
